<template>
  <div class="panel-tab__content">
    <el-form label-width="70px" @submit.native.prevent size="small">
      <el-radio-group v-model="approveMethod" @change="onApproveMethodChange">
      <div class="flex-col">
        <div v-for="(item, index) in APPROVE_METHODS" :key="index">
          <el-radio :value="item.value" :label="item.value">
            {{ item.label }}
          </el-radio>
          <el-form-item prop="approveRatio">
            <el-input-number
              v-model="approveRatio"
              :min="10"
              :max="100"
              :step="10"
              size="small"
              v-if="
                item.value === ApproveMethodType.APPROVE_BY_RATIO &&
                approveMethod === ApproveMethodType.APPROVE_BY_RATIO
              "
              @change="onApproveRatioChange"
            />
          </el-form-item>
        </div>
      </div>
    </el-radio-group>
    </el-form>
    <el-form label-width="90px" style="display: none">
      <el-form-item label="快捷配置">
        <el-button size="small" @click="changeConfig('依次审批')">依次审批</el-button>
        <el-button size="small" @click="changeConfig('会签')">会签</el-button>
        <el-button size="small" @click="changeConfig('或签')">或签</el-button>
      </el-form-item>
      <el-form-item label="会签类型">
        <el-select v-model="loopCharacteristics" @change="changeLoopCharacteristicsType">
          <el-option label="并行多重事件" value="ParallelMultiInstance" />
          <el-option label="时序多重事件" value="SequentialMultiInstance" />
          <el-option label="无" value="Null" />
        </el-select>
      </el-form-item>
      <template
        v-if="
          loopCharacteristics === 'ParallelMultiInstance' ||
          loopCharacteristics === 'SequentialMultiInstance'
        "
      >
        <el-form-item label="循环数量" key="loopCardinality">
          <el-input
            v-model="loopInstanceForm.loopCardinality"
            clearable
            @change="updateLoopCardinality"
          />
        </el-form-item>
        <el-form-item label="集合" key="collection" v-show="false">
          <el-input v-model="loopInstanceForm.collection" clearable @change="updateLoopBase" />
        </el-form-item>
        <!-- add by 芋艿：由于「元素变量」暂时用不到，所以这里 display 为 none -->
        <el-form-item label="元素变量" key="elementVariable" style="display: none">
          <el-input v-model="loopInstanceForm.elementVariable" clearable @change="updateLoopBase" />
        </el-form-item>
        <el-form-item label="完成条件" key="completionCondition">
          <el-input
            v-model="loopInstanceForm.completionCondition"
            clearable
            @change="updateLoopCondition"
          />
        </el-form-item>
        <!-- add by 芋艿：由于「异步状态」暂时用不到，所以这里 display 为 none -->
        <el-form-item label="异步状态" key="async" style="display: none">
          <el-checkbox
            v-model="loopInstanceForm.asyncBefore"
            label="异步前"
            value="异步前"
            @change="updateLoopAsync('asyncBefore')"
          />
          <el-checkbox
            v-model="loopInstanceForm.asyncAfter"
            label="异步后"
            value="异步后"
            @change="updateLoopAsync('asyncAfter')"
          />
          <el-checkbox
            v-model="loopInstanceForm.exclusive"
            v-if="loopInstanceForm.asyncAfter || loopInstanceForm.asyncBefore"
            label="排除"
            value="排除"
            @change="updateLoopAsync('exclusive')"
          />
        </el-form-item>
        <el-form-item
          label="重试周期"
          prop="timeCycle"
          v-if="loopInstanceForm.asyncAfter || loopInstanceForm.asyncBefore"
          key="timeCycle"
        >
          <el-input v-model="loopInstanceForm.timeCycle" clearable @change="updateLoopTimeCycle" />
        </el-form-item>
      </template>
    </el-form>

  </div>
</template>
<script>
import {StrUtil} from '@/utils/StrUtil'


export default {
  name: "MultiInstance",
  /** 组件传值  */
  props: {
    id: {
      type: String,
      required: true
    },
  },
  data() {
    return {

      otherExtensionList: [],
      ApproveMethodType:{
      RANDOM_SELECT_ONE_APPROVE : 1,//随机挑选一人审批
      APPROVE_BY_RATIO : 2,//多人会签(按通过比例)
      ANY_APPROVE : 3,//多人或签(通过只需一人，拒绝只需一人)
      SEQUENTIAL_APPROVE : 4//多人依次审批
      },
      APPROVE_METHODS:  [
        { label: '按顺序依次审批', value: 4 },
        // { label: '会签（可同时审批，至少 % 人必须审批通过）', value: 2 },
        { label: '或签(可同时审批，有一人通过即可)', value: 3 },
        { label: '随机挑选一人审批', value: 1 }
      ],
      approveMethod:"",
      approveRatio:100,
      dialogVisible: false,
      loopCharacteristics: "",
    
      loopInstanceForm: {},
      multiLoopInstance: {},
      defaultLoopInstanceForm: {
        completionCondition: "",
        loopCardinality: "",
        extensionElements: [],
        asyncAfter: false,
        asyncBefore: false,
        exclusive: false
      },
    }
  },

  /** 传值监听 */
  watch: {
    id: {
      handler(newVal) {
        if (StrUtil.isNotBlank(newVal)) {
         
          this.getElementLoop(this.modelerStore.element.businessObject);        }
      },
      immediate: true, // 立即生效
    },
  },
  created() {

  },
  methods: {
    // 方法区
    getElementLoop(businessObject) {
     
       this.approveMethod =businessObject?.extensionElements?.values?.filter(
    (ex) => ex.$type === `flowable:ApproveMethod`
  )?.[0]?.value;
   //var bb =businessObject?.extensionElements?.values
    this.otherExtensionList=[];
   console.log("多实例vue",businessObject?.extensionElements?.values);

   
      businessObject?.extensionElements?.values?.filter(ex => {
          if (ex.$type !== `flowable:ApproveMethod`) {
            this.otherExtensionList.push(ex);
          }
          return ex.$type === `flowable:Properties`;
        }) ?? [];
      if (!businessObject.loopCharacteristics) {
        this.loopCharacteristics = "Null";
        this.loopInstanceForm = {};
        return;
      }
      if (businessObject.loopCharacteristics.$type === "bpmn:StandardLoopCharacteristics") {
        this.loopCharacteristics = "StandardLoop";
        this.loopInstanceForm = {};
        return;
      }
      if (businessObject.loopCharacteristics.isSequential) {
        this.loopCharacteristics = "SequentialMultiInstance";
      } else {
        this.loopCharacteristics = "ParallelMultiInstance";
      }
      // 合并配置
      this.loopInstanceForm = {
        ...this.defaultLoopInstanceForm,
        ...businessObject.loopCharacteristics,
        completionCondition: businessObject.loopCharacteristics?.completionCondition?.body ?? "",
        loopCardinality: businessObject.loopCharacteristics?.loopCardinality?.body ?? ""
      };
      // 保留当前元素 businessObject 上的 loopCharacteristics 实例
      this.multiLoopInstance = this.modelerStore.element.businessObject.loopCharacteristics;
      // 更新表单
      if (
        businessObject.loopCharacteristics.extensionElements &&
        businessObject.loopCharacteristics.extensionElements.values &&
        businessObject.loopCharacteristics.extensionElements.values.length
      ) {
        this.$set(this.loopInstanceForm, "timeCycle", businessObject.loopCharacteristics.extensionElements.values[0].body);
      }
    },

    changeLoopCharacteristicsType(type) {
      
      // 切换类型取消原表单配置
      this.loopInstanceForm = {...this.defaultLoopInstanceForm};
      // 取消多实例配置
      if (type === "Null") {
        this.modelerStore.modeling.updateProperties(this.modelerStore.element, {loopCharacteristics: null});
        return;
      }
      // 配置循环
      if (type === "StandardLoop") {
        const loopCharacteristicsObject = this.modelerStore.moddle.create("bpmn:StandardLoopCharacteristics");
        this.modelerStore.modeling.updateProperties(this.modelerStore.element, {
          loopCharacteristics: loopCharacteristicsObject
        });
        this.multiLoopInstance = null;
        return;
      }
      // 时序
      if (type === "SequentialMultiInstance") {
        this.multiLoopInstance = this.modelerStore.moddle.create("bpmn:MultiInstanceLoopCharacteristics", {
          isSequential: true
        });
      } else {
        this.multiLoopInstance = this.modelerStore.moddle.create("bpmn:MultiInstanceLoopCharacteristics");
      }
      this.modelerStore.modeling.updateProperties(this.modelerStore.element, {
        loopCharacteristics: this.multiLoopInstance
      });
    },

    // 循环基数
    updateLoopCardinality(cardinality) {
      let loopCardinality = null;
      if (cardinality && cardinality.length) {
        loopCardinality = this.modelerStore.moddle.create("bpmn:FormalExpression", {body: cardinality});
      }
      this.modelerStore.modeling.updateModdleProperties(this.modelerStore.element, this.multiLoopInstance, {
        loopCardinality
      });
    },

    // 完成条件
    updateLoopCondition(condition) {
      let completionCondition = null;
      if (condition && condition.length) {
        completionCondition = this.modelerStore.moddle.create("bpmn:FormalExpression", {body: condition});
      }
      this.modelerStore.modeling.updateModdleProperties(this.modelerStore.element, this.multiLoopInstance, {
        completionCondition
      });
    },

    // 重试周期
    updateLoopTimeCycle(timeCycle) {
      const extensionElements = this.modelerStore.moddle.create("bpmn:ExtensionElements", {
        values: [
          this.modelerStore.moddle.create(`flowable:FailedJobRetryTimeCycle`, {
            body: timeCycle
          })
        ]
      });
      this.modelerStore.modeling.updateModdleProperties(this.modelerStore.element, this.multiLoopInstance, {
        extensionElements
      });
    },

    // 直接更新的基础信息
    updateLoopBase() {
      this.modelerStore.modeling.updateModdleProperties(this.modelerStore.element, this.multiLoopInstance, {
        collection: this.loopInstanceForm.collection || null,
        elementVariable: this.loopInstanceForm.elementVariable || null
      });
    },

    // 各异步状态
    updateLoopAsync(key) {
      const {asyncBefore, asyncAfter} = this.loopInstanceForm;
      let asyncAttr = Object.create(null);
      if (!asyncBefore && !asyncAfter) {
        this.$set(this.loopInstanceForm, "exclusive", false);
        asyncAttr = {asyncBefore: false, asyncAfter: false, exclusive: false, extensionElements: null};
      } else {
        asyncAttr[key] = this.loopInstanceForm[key];
      }
      this.modelerStore.modeling.updateModdleProperties(this.modelerStore.element, this.multiLoopInstance, asyncAttr);
    },

    onApproveMethodChange (){
      this.approveRatio = 100
      this.updateLoopCharacteristics()
    },
    updateLoopCharacteristics(){
           this.otherExtensionList=[];
          this.bpmnElement = this.modelerStore.element;
          this.bpmnElement.businessObject?.extensionElements?.values?.filter(ex => {
          if (ex.$type !== `flowable:ApproveMethod`) {
            this.otherExtensionList.push(ex);
          }
          return ex.$type === `flowable:Properties`;
        }) ?? [];
    

 // 根据ApproveMethod生成multiInstanceLoopCharacteristics节点
      if (this.approveMethod === this.ApproveMethodType.RANDOM_SELECT_ONE_APPROVE) {
          this.modelerStore.modeling.updateProperties(this.modelerStore.element, {
            loopCharacteristics: null
          })
        } else {
          if (this.approveMethod === this.ApproveMethodType.APPROVE_BY_RATIO) {
            this.multiLoopInstance = this.modelerStore.moddle.create(
              'bpmn:MultiInstanceLoopCharacteristics',
              { isSequential: false, collection: '${coll_userList}' }
            )
            this.multiLoopInstance.completionCondition = this.modelerStore.moddle.create(
              'bpmn:FormalExpression',
              {
                body: '${ nrOfCompletedInstances/nrOfInstances >= ' + this.approveRatio / 100 + '}'
              }
            )
          }
          if (this.approveMethod === this.ApproveMethodType.ANY_APPROVE) {
            this.multiLoopInstance = this.modelerStore.moddle.create(
              'bpmn:MultiInstanceLoopCharacteristics',
              { isSequential: false, collection: '${coll_userList}' }
            )
            this.multiLoopInstance.completionCondition = this.modelerStore.moddle.create(
              'bpmn:FormalExpression',
              {
                body: '${ nrOfCompletedInstances > 0 }'
              }
            )
          }
          if (this.approveMethod === this.ApproveMethodType.SEQUENTIAL_APPROVE) {
            this.multiLoopInstance = this.modelerStore.moddle.create(
              'bpmn:MultiInstanceLoopCharacteristics',
              { isSequential: true, collection: '${coll_userList}' }
            )
            this.multiLoopInstance.loopCardinality = this.modelerStore.moddle.create(
              'bpmn:FormalExpression',
              {
                body: '1'
              }
            )
            this.multiLoopInstance.completionCondition = this.modelerStore.moddle.create(
              'bpmn:FormalExpression',
              {
                body: '${ nrOfCompletedInstances >= nrOfInstances }'
              }
            )
          }
          //this.modelerStore.modeling.updateProperties(this.modelerStore.element, {loopCharacteristics: this.multiLoopInstance})
          this.modelerStore.modeling.updateProperties(this.modelerStore.element, {
              loopCharacteristics: this.multiLoopInstance
            });
  }


  const extensions = this.modelerStore.moddle.create('bpmn:ExtensionElements', {
    values: [
       ...this.otherExtensionList,
    this.modelerStore.moddle.create('flowable:ApproveMethod', {
        value: this.approveMethod
      })
    ]
  })
  this.modelerStore.modeling.updateProperties(this.modelerStore.element, {
    extensionElements: extensions
  })
    }
  }
}

</script>
<style lang="scss">
@import '../style/process-panel';
</style>

